﻿namespace WMS6.BLL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using WMS6.Common;
    using WMS6.DALFactory;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;

    public class PurchaseOrderDetailBLL
    {
        private static readonly ICommonMethodDA commonMethod = DataAccess.CreateCommonMethod();
        private List<string> dataBaseID;
        private static readonly IInvLotDA invLotDA = DataAccess.CreateInvLotDA();
        private static readonly IInvTransDA invTransDA = DataAccess.CreateInvTransDA();
        private static readonly IPackDA packDA = DataAccess.CreatePackDA();
        private PubParasInfo pubParasInfo;
        private static readonly IPurchaseOrderDA purchaseOrderDA = DataAccess.CreatePurchaseOrderDA();
        private static readonly IPurchaseOrderDetailDA purchaseOrderDetailDA = DataAccess.CreatePurchaseOrderDetailDA();
        private static readonly IReceiptDetailDA receiptDetailDA = DataAccess.CreateReceiptDetailDA();
        private static readonly IReceiptDetailLpnDA receiptDetailLpnDA = DataAccess.CreateReceiptDetailLpnDA();
        private static readonly ISkuDA skuDA = DataAccess.CreateSkuDA();

        public PurchaseOrderDetailBLL()
        {
            this.pubParasInfo = null;
        }

        public PurchaseOrderDetailBLL(string currentWH)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(currentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(currentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001");
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002");
            }
        }

        public PurchaseOrderDetailBLL(PubParasInfo tempPubParasInfo)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(tempPubParasInfo.CurrentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(tempPubParasInfo.CurrentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001", this.pubParasInfo.UserLanguage);
                }
                else
                {
                    this.pubParasInfo = new PubParasInfo();
                    this.pubParasInfo = tempPubParasInfo;
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002", this.pubParasInfo.UserLanguage);
            }
        }

        public string DeleteDetail(List<string> poIDs, List<string> lineIDs)
        {
            string temp = string.Empty;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                int i;
                if (poIDs.Count != lineIDs.Count)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("F3100_009", this.pubParasInfo.UserLanguage);
                }
                List<PurchaseOrderDetailInfo> purchaseOrderDetailInfos = new List<PurchaseOrderDetailInfo>();
                PurchaseOrderDetailInfo purchaseOrderDetailInfo = null;
                for (i = 0; i < poIDs.Count; i++)
                {
                    purchaseOrderDetailInfo = purchaseOrderDetailDA.GetPurchaseOrderDetailByID(dataBase, tran, poIDs[i], lineIDs[i], this.dataBaseID[0], this.pubParasInfo);
                    purchaseOrderDetailInfos.Add(purchaseOrderDetailInfo);
                }
                AuditDataBLL auditDataBLL = new AuditDataBLL();
                if (purchaseOrderDetailDA.DeletePurchaseOrderDetail(dataBase, tran, poIDs, lineIDs, this.dataBaseID) > 0)
                {
                    for (i = 0; i < poIDs.Count; i++)
                    {
                        auditDataBLL.InsertAuditData<PurchaseOrderDetailInfo>(dataBase, tran, purchaseOrderDetailInfos[i], null, AuditAction.Delete, this.pubParasInfo.UserID, "PURCHASE_ORDER_DETAIL", this.dataBaseID[0]);
                        temp = temp + poIDs[i] + "," + lineIDs[i];
                    }
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            if (temp.Length > 0)
            {
                return temp.Substring(0, temp.Length - 1);
            }
            return "";
        }

        public DataSet GetAllpurchaseOrderDetailInfo()
        {
            return purchaseOrderDetailDA.GetAllPurchaseOrderDetail(this.dataBaseID[0], this.pubParasInfo);
        }

        public PurchaseOrderDetailInfo GetDetailInfoByID(string poID, string lineID)
        {
            PurchaseOrderDetailInfo purchaseOrderDetailInfo = purchaseOrderDetailDA.GetPurchaseOrderDetailByID(poID, lineID, this.dataBaseID[0], this.pubParasInfo);
            if (purchaseOrderDetailInfo != null)
            {
                InboundHelper inboundHelper = new InboundHelper();
                PackInfo packInfo = packDA.GetPackByID(purchaseOrderDetailInfo.PackID, this.dataBaseID[0]);
                purchaseOrderDetailInfo.OrderedQty = inboundHelper.ExchangeUom(packInfo, purchaseOrderDetailInfo.UomID, purchaseOrderDetailInfo.OrderedQty, "R");
                purchaseOrderDetailInfo.AdjustedQty = inboundHelper.ExchangeUom(packInfo, purchaseOrderDetailInfo.UomID, purchaseOrderDetailInfo.AdjustedQty, "R");
                purchaseOrderDetailInfo.ReceivedQty = inboundHelper.ExchangeUom(packInfo, purchaseOrderDetailInfo.UomID, purchaseOrderDetailInfo.ReceivedQty, "R");
                purchaseOrderDetailInfo.RejectedQty = inboundHelper.ExchangeUom(packInfo, purchaseOrderDetailInfo.UomID, purchaseOrderDetailInfo.RejectedQty, "R");
            }
            return purchaseOrderDetailInfo;
        }

        public List<PurchaseOrderDetailInfo> GetDetailInfoListByID(string poID)
        {
            return purchaseOrderDetailDA.GetPurchaseOrderDetailListByID(poID, this.dataBaseID[0], this.pubParasInfo);
        }

        public string InsertDetail(PurchaseOrderDetailInfo purchaseOrderDetailInfo)
        {
            PurchaseOrderDetailInfo purchaseOrderDetail = purchaseOrderDetailInfo;
            string lineID = string.Empty;
            try
            {
                if (purchaseOrderDetail == null)
                {
                    return lineID;
                }
                if (purchaseOrderDetailDA.CheckPurchaseOrderDetailIDUnique(purchaseOrderDetail.PoID, purchaseOrderDetail.LineID.ToString(), this.dataBaseID[0]))
                {
                    PublicMethod.GetInstance().ShowAlertMessage("F3100_007", this.pubParasInfo.UserLanguage, new List<string> { purchaseOrderDetail.PoID, purchaseOrderDetail.LineID.ToString() });
                }
                if (!skuDA.CheckSkuIDUnique(purchaseOrderDetail.OwnerID, purchaseOrderDetail.SkuID, this.dataBaseID[0]))
                {
                    PublicMethod.GetInstance().ShowAlertMessage("F4200_011", this.pubParasInfo.UserLanguage, new List<string> { purchaseOrderDetail.SkuID });
                }
                purchaseOrderDetail.OrderedQty = new InboundHelper().ExchangeUom(purchaseOrderDetail.PackID, purchaseOrderDetail.UomID, purchaseOrderDetail.OrderedQty, "W", this.dataBaseID[0]);
                purchaseOrderDetail.UpdatedBy = purchaseOrderDetail.CreatedBy;
                purchaseOrderDetail.CreatedDate = DateTime.Now;
                purchaseOrderDetail.UpdatedDate = DateTime.Now;
                if (purchaseOrderDetailDA.InsertPurchaseOrderDetail(purchaseOrderDetail, this.dataBaseID) > 0)
                {
                    new AuditDataBLL().InsertAuditData<PurchaseOrderDetailInfo>(null, purchaseOrderDetail, AuditAction.Insert, this.pubParasInfo.UserID, "PURCHASE_ORDER_DETAIL", this.dataBaseID[0]);
                    lineID = purchaseOrderDetail.LineID.ToString();
                }
            }
            catch (Exception ex)
            {
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            return lineID;
        }

        public string purchaseOrderDetailImportByData(string[][] ImportByData)
        {
            Exception ex;
            string LocIDTrue = string.Empty;
            string LocIDFalse = string.Empty;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                int iLineID = 0;
                for (int i = 1; ImportByData.Length > i; i++)
                {
                    PurchaseOrderDetailInfo purchaseOrderDetailInfo = new PurchaseOrderDetailInfo();
                    for (int n = 0; ImportByData[i].Length > n; n++)
                    {
                        try
                        {
                            string CS40001 = ImportByData[0][n].ToUpper();
                            if (CS40001 != null)
                            {
                                if (!(CS40001 == "SKU"))
                                {
                                    if (CS40001 == "QTY")
                                    {
                                        goto Label_00C0;
                                    }
                                    if (CS40001 == "OWNERID")
                                    {
                                        goto Label_00ED;
                                    }
                                    if (CS40001 == "ORDERID")
                                    {
                                        goto Label_0112;
                                    }
                                }
                                else if (!string.IsNullOrEmpty(ImportByData[i][n]))
                                {
                                    purchaseOrderDetailInfo.SkuID = ImportByData[i][n];
                                }
                            }
                            continue;
                        Label_00C0:
                            if (!string.IsNullOrEmpty(ImportByData[i][n]))
                            {
                                purchaseOrderDetailInfo.OrderedQty = Convert.ToDecimal(ImportByData[i][n]);
                            }
                            continue;
                        Label_00ED:
                            if (!string.IsNullOrEmpty(ImportByData[i][n]))
                            {
                                purchaseOrderDetailInfo.OwnerID = ImportByData[i][n];
                            }
                            continue;
                        Label_0112:
                            if (!string.IsNullOrEmpty(ImportByData[i][n]))
                            {
                                purchaseOrderDetailInfo.PoID = ImportByData[i][n];
                                if (iLineID == 0)
                                {
                                    iLineID = commonMethod.GetMaxLineID("PURCHASE_ORDER_DETAIL", purchaseOrderDetailInfo.PoID, this.dataBaseID[0]) + 10;
                                }
                                else
                                {
                                    iLineID += 10;
                                }
                                purchaseOrderDetailInfo.LineID = iLineID;
                            }
                        }
                        catch (Exception exception1)
                        {
                            ex = exception1;
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "（内容异常:" + ex.Message + ")");
                        }
                    }
                    if (string.IsNullOrEmpty(purchaseOrderDetailInfo.PoID))
                    {
                        throw new Exception("（导入异常:主单据未保存");
                    }
                    try
                    {
                        purchaseOrderDetailInfo.Status = "New";
                        purchaseOrderDetailInfo.ReceivedQty = 0M;
                        purchaseOrderDetailInfo.RejectedQty = 0M;
                        purchaseOrderDetailInfo.QcAutoAdjust = "N";
                        purchaseOrderDetailInfo.QcRequired = "N";
                        purchaseOrderDetailInfo.Udf1 = "";
                        purchaseOrderDetailInfo.Udf2 = "";
                        purchaseOrderDetailInfo.Udf3 = "";
                        purchaseOrderDetailInfo.Udf4 = "";
                        purchaseOrderDetailInfo.Udf5 = "";
                        purchaseOrderDetailInfo.Udf6 = "";
                        purchaseOrderDetailInfo.Udf7 = "";
                        purchaseOrderDetailInfo.Udf8 = "";
                        purchaseOrderDetailInfo.Udf9 = "";
                        purchaseOrderDetailInfo.Udf10 = "";
                        purchaseOrderDetailInfo.Remark = "";
                        if (!DataAccess.CreateOwnerDA().CheckTradePartnerIDUnique(purchaseOrderDetailInfo.OwnerID, this.dataBaseID[0]))
                        {
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "( 货主" + purchaseOrderDetailInfo.OwnerID + ")不存在,导入失败);");
                        }
                        if (!commonMethod.CheckAuthorizationOwnerByUserID(this.pubParasInfo.UserID, purchaseOrderDetailInfo.OwnerID))
                        {
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "( 货主" + purchaseOrderDetailInfo.OwnerID + ")没有权限,导入失败);");
                        }
                        SkuInfo skuInfo = skuDA.GetSkuByID(dataBase, tran, purchaseOrderDetailInfo.OwnerID, purchaseOrderDetailInfo.SkuID, this.dataBaseID[0]);
                        if (skuInfo == null)
                        {
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "( 货主" + purchaseOrderDetailInfo.OwnerID + "  Sku(货品 " + purchaseOrderDetailInfo.SkuID + ")不存在,导入失败");
                        }
                        if (skuInfo.IsActive != "Y")
                        {
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "( 货主" + purchaseOrderDetailInfo.OwnerID + "  Sku(货品 " + purchaseOrderDetailInfo.SkuID + ")未启用,导入失败");
                        }
                        purchaseOrderDetailInfo.SkuDesc = skuInfo.Descr;
                        purchaseOrderDetailInfo.AltSkuID = "";
                        purchaseOrderDetailInfo.PackID = skuInfo.PackID;
                        if (!string.IsNullOrEmpty(purchaseOrderDetailInfo.PackID))
                        {
                            PackInfo packInfo = packDA.GetPackByID(dataBase, tran, purchaseOrderDetailInfo.PackID, this.dataBaseID[0]);
                            purchaseOrderDetailInfo.UomID = packInfo.PackUom1;
                        }
                        purchaseOrderDetailInfo.TotalGrossWeight = Convert.ToSingle((decimal) (Convert.ToDecimal(skuInfo.GrossWgt) * purchaseOrderDetailInfo.OrderedQty));
                        purchaseOrderDetailInfo.TotalNetWeight = Convert.ToSingle((decimal) (Convert.ToDecimal(skuInfo.NetWgt) * purchaseOrderDetailInfo.OrderedQty));
                        purchaseOrderDetailInfo.UnitPrice = Convert.ToSingle(skuInfo.CostPrice);
                        purchaseOrderDetailInfo.TotalPrice = Convert.ToSingle((decimal) (skuInfo.CostPrice * purchaseOrderDetailInfo.OrderedQty));
                        purchaseOrderDetailInfo.TotalCube = Convert.ToSingle((decimal) (Convert.ToDecimal(skuInfo.Cube) * purchaseOrderDetailInfo.OrderedQty));
                        purchaseOrderDetailInfo.CreatedBy = this.pubParasInfo.UserID;
                        purchaseOrderDetailInfo.UpdatedBy = purchaseOrderDetailInfo.CreatedBy;
                        if (purchaseOrderDetailDA.InsertPurchaseOrderDetail(dataBase, tran, purchaseOrderDetailInfo, this.dataBaseID) > 0)
                        {
                            LocIDTrue = LocIDTrue + purchaseOrderDetailInfo.SkuID + ";";
                        }
                    }
                    catch (Exception exception2)
                    {
                        ex = exception2;
                        if (!string.IsNullOrEmpty(purchaseOrderDetailInfo.SkuID))
                        {
                            throw new Exception(purchaseOrderDetailInfo.SkuID + "（交互异常:" + ex.Message + "）");
                        }
                    }
                }
                tran.Commit();
            }
            catch (Exception exception3)
            {
                ex = exception3;
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return LocIDFalse;
        }

        public string purchaseOrderDetailPriceChanges(string PoID, string poLineID, float price, float totalprice)
        {
            string strtemp = string.Empty;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                purchaseOrderDetailDA.PurchaseOrderDetailPriceChanges(dataBase, tran, PoID, poLineID, (double) price, totalprice, this.dataBaseID[0], this.pubParasInfo.UserID);
                List<ReceiptDetailInfo> receiptDetailList = receiptDetailDA.GetReceiptDetailListByPoID(dataBase, tran, PoID, poLineID, this.dataBaseID[0], this.pubParasInfo);
                if ((receiptDetailList != null) && (receiptDetailList.Count > 0))
                {
                    foreach (ReceiptDetailInfo info in receiptDetailList)
                    {
                        info.UnitPrice = price;
                        info.UpdatedBy = this.pubParasInfo.UserID;
                        receiptDetailDA.UpdateReceiptDetail(dataBase, tran, info, this.dataBaseID[0]);
                        List<InvTransInfo> invtransinfo = invTransDA.GetInvTransListByReceiptID(dataBase, tran, info.ReceiptID, info.ReceiptLineID.ToString(), this.dataBaseID[0], this.pubParasInfo);
                        if ((invtransinfo != null) && (invtransinfo.Count > 0))
                        {
                            foreach (InvTransInfo Invinfo in invtransinfo)
                            {
                                invTransDA.UpdateInvTransUnitPriceByLot(dataBase, tran, Invinfo.Lot, price, this.dataBaseID[0], this.pubParasInfo.UserID);
                                invLotDA.UpdateInvLotUnitPriceBylot(dataBase, tran, Invinfo.Lot, price, this.pubParasInfo.UserID, this.dataBaseID[0]);
                            }
                        }
                    }
                }
                else
                {
                    List<ReceiptDetailInfo> receiptDetailLpnList = receiptDetailLpnDA.GetReceiptDetailListByPoID(dataBase, tran, PoID, poLineID, this.dataBaseID[0], this.pubParasInfo);
                    if ((receiptDetailLpnList != null) && (receiptDetailLpnList.Count > 0))
                    {
                        foreach (ReceiptDetailInfo info in receiptDetailLpnList)
                        {
                            info.UnitPrice = price;
                            info.UpdatedBy = this.pubParasInfo.UserID;
                            receiptDetailLpnDA.UpdateReceiptDetailLpn(dataBase, tran, info, this.dataBaseID[0]);
                            InvTransInfo invtransinfo = invTransDA.GetInvTransByReceiptID(dataBase, tran, info.ReceiptID, info.ReceiptLineID.ToString(), this.dataBaseID[0], this.pubParasInfo);
                            if (invtransinfo != null)
                            {
                                invTransDA.UpdateInvTransUnitPriceByLot(dataBase, tran, invtransinfo.Lot, price, this.dataBaseID[0], this.pubParasInfo.UserID);
                                invLotDA.UpdateInvLotUnitPriceBylot(dataBase, tran, invtransinfo.Lot, price, this.pubParasInfo.UserID, this.dataBaseID[0]);
                            }
                        }
                    }
                    else
                    {
                        strtemp = PoID + "未找到对应的数据源！";
                    }
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return strtemp;
        }

        public string UpdateDetail(PurchaseOrderDetailInfo purchaseOrderDetailInfo)
        {
            string lineID = string.Empty;
            try
            {
                purchaseOrderDetailInfo.CreatedDate = DateTime.Now;
                purchaseOrderDetailInfo.UpdatedBy = this.pubParasInfo.UserID;
                purchaseOrderDetailInfo.UpdatedDate = DateTime.Now;
                if (purchaseOrderDetailInfo.OrderedQty <= purchaseOrderDetailInfo.ReceivedQty)
                {
                    purchaseOrderDetailInfo.Status = "ReceivedComplete";
                }
                PurchaseOrderDetailInfo oldPurchaseOrderDetailInfo = purchaseOrderDetailDA.GetPurchaseOrderDetailByID(purchaseOrderDetailInfo.PoID, purchaseOrderDetailInfo.LineID.ToString(), this.dataBaseID[0], this.pubParasInfo);
                if (purchaseOrderDetailDA.UpdatePurchaseOrderDetail(purchaseOrderDetailInfo, this.dataBaseID) > 0)
                {
                    List<PurchaseOrderDetailInfo> purchaseOrderDetailList = purchaseOrderDetailDA.GetPurchaseOrderDetailListByID(purchaseOrderDetailInfo.PoID, this.dataBaseID[0], this.pubParasInfo);
                    string strStatus = new InboundHelper().GetPurchaseOrderStatus(purchaseOrderDetailList);
                    purchaseOrderDA.UpdatePurchaseOrderStatus(purchaseOrderDetailInfo.PoID, strStatus, this.dataBaseID[0], this.pubParasInfo.UserID);
                    new AuditDataBLL().InsertAuditData<PurchaseOrderDetailInfo>(oldPurchaseOrderDetailInfo, purchaseOrderDetailInfo, AuditAction.Update, this.pubParasInfo.UserID, "PURCHASE_ORDER_DETAIL", this.dataBaseID[0]);
                    lineID = purchaseOrderDetailInfo.LineID.ToString();
                }
            }
            catch (Exception ex)
            {
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            return lineID;
        }
    }
}

